import React from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'

class App extends React.Component {
  state = {
    list: [
      {
        id: 1,
        name: '鲁迅',
        content: '时间就是生命',
      },
      {
        id: 2,
        name: '林则徐',
        content: '苟利国家生死以',
      },
      {
        id: 3,
        name: '李白',
        content: '安能摧眉折腰事权贵',
      },
    ],
    username: '',
    usercontent: '',
  }

  //渲染评论
  renderList() {
    const { list } = this.state
    if (list.length === 0) {
      return <div>暂无评论~~</div>
    }
    return (
      <ul>
        {list.map((item) => (
          <li key={item.id}>
            <h3>评论人：{item.name}</h3>
            <p>评论内容：{item.content}</p>
            <button
              onClick={() => {
                this.delete(item.id)
              }}
            >
              删除
            </button>
          </li>
        ))}
      </ul>
    )
  }

  //删除评论函数
  delete = (id) => {
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    })
  }

  //绑定清空评论函数
  clear = () => {
    this.setState({
      list: [],
    })
  }

  //handlleChange函数
  handlleChange = (e) => {
    // console.log(e.target)
    const { name, value } = e.target
    this.setState({
      [name]: value,
    })
  }

  //添加评论
  add = () => {
    // console.log(11)
    const { list, username, usercontent } = this.state
    if (usercontent === '' || username === '') {
      return alert('内容不能为空！')
    }
    this.setState({
      list: [
        {
          id: Date.now(),
          name: username,
          content: usercontent,
        },
        ...list,
      ],
      username: '',
      usercontent: '',
    })
  }

  render() {
    return (
      <div className="app">
        <div>
          <input
            className="user"
            type="text"
            placeholder="请输入评论人"
            name="username"
            value={this.state.username}
            onChange={this.handlleChange}
          />
          <br />
          <textarea
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
            name="usercontent"
            value={this.state.usercontent}
            onChange={this.handlleChange}
          />
          <br />
          <button onClick={this.add}>发表评论</button>
          <button onClick={this.clear}>清空评论</button>
        </div>
        {this.renderList()}
      </div>
    )
  }
}

// 渲染组件
// ReactDOM.render(<App />, document.getElementById('root'))
createRoot(document.querySelector('#root')).render(<App />)
